/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package proyecto.controlador;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;
import proyecto.modelo.Restaurante;
import proyecto.modelo.Usuario;

/**
 *
 * @author javaee
 */
public class DMLServlet extends HttpServlet {
    @Resource(name = "dataSource")
    private DataSource dataSource;
    private static final String ACTION_NEW = "create";
    private static final String ACTION_EDIT = "edit";
    private static final String ACTION_REMOVE = "remove";
    private static final String RESPUESTA = "respuesta";
    private static final String ERRORES = "errores";
    
    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        String action = request.getParameter("action");
        String idrestaurante = request.getParameter("idrestaurante");
        String restaurante = request.getParameter("restaurante");
        String direccion = request.getParameter("direccion");
        String telefono = request.getParameter("telefono");
        String errorPage = request.getParameter("errorPage");
        String viewPage = request.getParameter("viewPage");
        
        Restaurante respuesta = null;
        List<String> errores = new ArrayList<String>(0);
        String outcome = null;
        HttpSession session = request.getSession();
        
        boolean actionVal = action != null && action.length() > 0;
        boolean idVal = idrestaurante != null && idrestaurante.length() > 0;
        boolean restaurantetVal = restaurante != null && restaurante.length() == 10;
        boolean direccionVal = direccion != null && direccion.length() > 0;
        boolean telefonoVal = telefono != null && telefono.length() > 0;
        
        Connection conn = null;
        PreparedStatement psta1=null; 
        ResultSet rset = null;
        Restaurante  re= null;
        try {
            conn = dataSource.getConnection();
            if (action.equals(ACTION_NEW)) 
            {
              psta1 = conn.prepareStatement(Restaurante.getINSERT());
              psta1.setString(1,restaurante);
              psta1.setString(2,direccion);
              psta1.setString(3,telefono);
            }
            if (action.equals(ACTION_EDIT) && idVal) {
                psta1 = conn.prepareStatement(Restaurante.getUPDATE());
                psta1.setString(1,restaurante);
                psta1.setString(2,direccion);
                psta1.setString(3,telefono);
                psta1.setString(4,idrestaurante);
                
            }
            
            if (action.equals(ACTION_REMOVE) && idVal) {
                psta1 = conn.prepareStatement(Restaurante.getDELETE());
                psta1.setString(1,idrestaurante);
                
            }
            
            
            psta1.executeUpdate();
            psta1.close();
            
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally{
          try {
                if (conn != null) {
                    conn.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
           if(!action.equals("nombres")){buscarTodos(request,response);}
           else{buscarNombre(request, response);}
        }
        
        

    }
    
    protected void buscarTodos(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        
      String outcome = null;
      List<Restaurante> respuesta = new ArrayList<Restaurante>(0);
      HttpSession session = request.getSession();
      Connection conn = null;
      PreparedStatement psta1=null; 
      ResultSet rset = null;
      try {
        
          conn = dataSource.getConnection();
          psta1 = conn.prepareStatement(Restaurante.getSELECT_ALL());
          rset = psta1.executeQuery();
          while (rset.next()) {

                Restaurante dto = new Restaurante();

                dto.setIdrestaurante(rset.getInt("idrestaurante"));
                dto.setRestaurante(rset.getString("restaurante"));
                dto.setDireccion(rset.getString("direccion"));
                dto.setTelefono(rset.getString("telefono"));
                respuesta.add(dto);
            }
            rset.close();
            psta1.close();    
            session.setAttribute("respuestaGrid", respuesta);
      } catch (Exception e) {
        e.printStackTrace();
      }finally {

            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
       outcome="/app/principal.jsp";
       String url = response.encodeRedirectURL(this.getServletContext().getContextPath() + outcome);
       response.sendRedirect(url); 
    }
   
    protected void buscarNombre(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
     
      String nombres = request.getParameter("nombres");
      
      String outcome = null;
      List<Restaurante> respuesta = new ArrayList<Restaurante>(0);
      List<String> errores = new ArrayList<String>(0);
      HttpSession session = request.getSession();
      Connection conn = null;
      PreparedStatement psta1=null; 
      ResultSet rset = null;
//      session.setAttribute("sql","select * from restaurantre where restaurante like '%"+nombres+"%'");
      boolean nombresVal = nombres != null && nombres.length() > 0;
      if(nombresVal)
      {
        try {
          conn = dataSource.getConnection();
          psta1 = conn.prepareStatement("select * from restaurante where restaurante like '%"+nombres+"%'");
          rset = psta1.executeQuery();
          while (rset.next()) {

                Restaurante dto = new Restaurante();

                dto.setIdrestaurante(rset.getInt("idrestaurante"));
                dto.setRestaurante(rset.getString("restaurante"));
                dto.setDireccion(rset.getString("direccion"));
                dto.setTelefono(rset.getString("telefono"));
                respuesta.add(dto);
            }
            rset.close();
            psta1.close();    
            session.setAttribute("respuestaGrid", respuesta);
           
            
        } catch (Exception e) {
        }finally {

            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
       outcome="/app/principal.jsp";
       String url = response.encodeRedirectURL(this.getServletContext().getContextPath() + outcome);
       response.sendRedirect(url); 
      }
      else
      {
       errores.add("Error debe ingresar un valor de busqueda");
      }
    }
    
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
